<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SystemLog;
use App\Traits\Controllers\IndexTraits;
use App\Transformers\System\SystemLogTransformer;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;

class SafetyProtectController extends Controller
{

    public $model = SystemLog::class;

    public $transformer = SystemLogTransformer::class;

    /**
     * 清除缓存
     */
    public function cacheClear()
    {
        Artisan::call('cache:clear');

        return $this->response->noContent();
    }

    /**
     * 清除系统日志
     */
    public function systemLogclear()
    {
        Artisan::call('systemLog:clear');

        return $this->response->noContent();
    }

    /**
     * 系统管理员操作日志列表
     */
    public function index(Request $request)
    {

        //先处理传过来的搜索数据
        $this->formatIndexQuery($request);

        $product_name = $request->input('product_name');
        $request->offsetUnset('product_name');

        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');

        //获取传过来的时间类型
        $time = $request->input('time');


        $data = $this
            ->getQuery()
            ->pimp()//自动转换where条件
            ->when($time || ($start_time && $end_time), function ($query) use ($time,$start_time,$end_time) {
                //自定义时间
                if(!empty($start) && !empty($stop)){
                    $query->whereBetween('created_at',[$start,$stop]);
                }

                //搜索今天数据
                if ($time == "today") {
                    $query->whereBetween('created_at', [Carbon::now()->startOfDay(), Carbon::now()->endOfDay()]);
                }

                //搜索昨天数据
                if ($time == "yesterday") {
                    $query->whereDay('created_at', [Carbon::now()->yesterday(), Carbon::now()->startOfDay()]);
                }

                //搜索最近一周数据
                if ($time == "week") {
                    $query->whereBetween('created_at', [Carbon::now()->subDays(7), Carbon::now()->subDays(0)]);
                }

                //搜索最近三十天数据
                if ($time == "thirty") {
                    $query->whereBetween('created_at', [Carbon::now()->subDays(30), Carbon::now()->subDays(0)]);
                }

                //搜索本月数据
                if ($time == "month") {
                    $query->whereBetween('created_at', [Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth()]);
                }

                //搜索本年数据
                if ($time == "year") {
                    $query->whereBetween('created_at', [Carbon::now()->startOfYear(), Carbon::now()->endOfYear()]);
                }
            })
            ->paginate($this->getPageLimit());

        return $this->response->paginator($data, resolve($this->transformer));

    }

}
